package com.zhonghe.menglinetty.modbus4j_modbustcp;

import com.digitalpetri.modbus.codec.Modbus;
import com.digitalpetri.modbus.master.ModbusTcpMaster;
import com.digitalpetri.modbus.master.ModbusTcpMasterConfig;
import com.digitalpetri.modbus.requests.ReadHoldingRegistersRequest;
import com.digitalpetri.modbus.responses.ReadHoldingRegistersResponse;
import io.netty.util.ReferenceCountUtil;

import java.util.concurrent.CompletableFuture;

/**
 * Copyright (C) 广州中和互联网技术有限公司
 *
 * modbus异步读取测试
 * @author 范家微 fanjiawei@borche.cn
 * @date :2021/1/24 13:20
 */
public class ModBusAsnyTest {
	/**
	 * @Description TODO
	 * @Author www.moyundong.com
	 * @Date 2020/11/20 11:05
	 */
	public static void main(String[] args) throws Exception{
			asynReadHoldingRegisters(2,2,1);
		}

		public static void asynReadHoldingRegisters(int address, int quantity, int unitId){

			ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder("127.0.0.1").setPort(502).build();
			ModbusTcpMaster master = new ModbusTcpMaster(config);

			try{
				master.connect();

				CompletableFuture<ReadHoldingRegistersResponse> future =
						master.sendRequest(new ReadHoldingRegistersRequest(2, 2), 1);

				System.out.println("这个是异步方法---开始");
				future.thenAccept(response -> {
					System.out.println("这里是异步取值: " + response.getRegisters().readFloat());
					ReferenceCountUtil.release(response);
					//不能在异步方法外面直接断开连接，不然异步方法娶不到值。在什么情况下断开连接，大家根据自己实际业务
					master.disconnect();
					Modbus.releaseSharedResources();
				});
				System.out.println("这个是异步方法---结束");
			}catch (Exception e){
				System.out.println(e.getMessage());
			}finally {
				System.out.println("finally end");
			}
		}

}
